 -- @Author: Roger.zou
-- @Date:   2015-10-17 09:48:51
-- @Last Modified by:   anchen
-- @Last Modified time: 2015-12-20 15:32:42


--由于可能是windows 的Bug，修改的全局的环境变量不会立马生效，这点暂时无法解决
--目前提供2个方案弥补，一个是提供设定临时环境变量，这个在当前的shell是立马生效的
--提供设置全局永久环境变量的功能，需要重启或者编辑下环境变量触发生效
--按配置选项location 和flag 来安装


--显示用法  卸载、安装，卸载某部分，安装某部分，
--
--

-- wmic ENVIRONMENT where "name='PYTHONPATH' and username='<system>'" set VariableValue="D:\platform\Python27"
-- wmic ENVIRONMENT where "name='path' and username='<system>'" set VariableValue="%path%;%PYTHONPATH%"
function show_usage(  )
    
end



function Main_menu( lists)
    print("===================================================================================")
    print("                     <Unified develop environment Menu>\r\n")
    print( string.format("%-2d--[%s]",0, "quit" ) )    
    print( string.format("%-2d--[%s]",1, "clean") )  
    print( string.format("%-2d--[%s]",2, "temp-color black") )    
    print( string.format("%-2d--[%s]",3, "perment-green" ) )      
    print( string.format("%-2d--[%s]",4, "install all") )
    print( string.format("%-2d--[%s]",5, "uninstall all") )
  
    for i,item in ipairs(lists) do
        local menu = string.format("%-2d--[%-12s] %-12s %-16s %s %-12s", (i+5),"install/uninstall",item.name,item.env_base,"PATH:",item.root)
        print(menu)   
    end
    print("===================================================================================")
end


function Sub_menu(list )
    -- os.execute("cls")
    print( string.format("%-02d--[%s]",0,"quit") )
    print( string.format("%-02d--[%s]",1,"back") )  
    print( string.format("%-02d--[%s]",2,"install") )
    print( string.format("%-02d--[%s]",3,"uninstall") )
end


function get_choice( lists,max_value )
    -- body
    print("Please input number:")
    io.input(io.stdin)
    while true do
       choice = io.read("*line")
       value = tonumber(choice)
        if(value) and value <=max_value then
           return value
        else
           print("Error:input number error!") 
           print("Please input number:>")
        end
    end
end

--功能配置
--删除目录软链接并创建目录软链接到work
--添加到环境变量和root
--location：环境变量类型 'USER' or 'SYSTEM' 默认使用参数指定的类型，若未指定使用配置自带
--
function env_install( f,mode,location,base_dir,lists,index)



    target_dir = string.format("%s",lists[index].root) 
    link_dir = string.format("%s%s%s",base_dir,"\\work\\",lists[index].name)
	
	cmds = string.format("::=======%s  %s   %s=========\n",lists[index].name,lists[index].env_base,lists[index].root )
    f:write(cmds)
	
    -- cmds = string.format("@rmdir %s\r\n",link_dir )
    -- f:write(cmds)
    -- cmds = string.format("@mklink /D %s %s\r\n",link_dir,target_dir )
    -- f:write(cmds)

    cmds = string.format("@set %s=\n",lists[index].env_base )
    f:write(cmds)
    cmds = string.format("@set %s=%s\n",lists[index].env_base,lists[index].root )
    f:write(cmds)
	if mode ~= 0 then  --永久设置环境变量
		cmds = string.format("@wmic ENVIRONMENT where \"name='%s' and username='<%s>'\" DELETE \n",lists[index].env_base,location )
		f:write(cmds)
		cmds = string.format("wmic ENVIRONMENT create name=\"%s\",username=\"<%s>\",VariableValue=\"%s\"\n",lists[index].env_base,location,lists[index].root )
		f:write(cmds)
        f:write("\r\n")
	end
   
    for i,v in ipairs(lists[index].env_ext) do
	    cmds = string.format("@set %s=%%%s%%\\%s;%%%s%%\n",v.env_name,lists[index].env_base,v.path,v.env_name)
        f:write(cmds)
	
		if mode ~= 0  then  --永久设置环境变量
			cmds = string.format("@wmic ENVIRONMENT where \"name='%s' and username='<%s>'\" DELETE \n",v.env_name,location )
			f:write(cmds)
			cmds = string.format("wmic ENVIRONMENT create name=\"%s\",username=\"<%s>\",VariableValue=\"%%%s%%\"\n",v.env_name,location,v.env_name )
			f:write(cmds)
            f:write("\r\n")
		end
    end

	f:write("\r\n\r\n")


end

--功能配置
--
--
function env_uninstall(f,location,base_dir,lists,index)

    target_dir = string.format("%s",lists[index].root) 
    link_dir = string.format("%s%s%s",base_dir,"\\work\\",lists[index].name)

    cmds = string.format("@rmdir %s",link_dir )
    print(cmds)
    os.execute(cmds)
	if mode ~= 0 then  --永久设置环境变量
	end

    percent='%'
    for i,v in ipairs(lists[index].env_ext) do
        cmds = string.format("cscript.exe bin\\Env.vbs -r %s %s %s%s%s\\%s;","SYSTEM",v.env_name,percent,lists[index].env_base,percent,v.path)
        print(cmds)
        os.execute(cmds)
    end
    cmds = string.format("cscript.exe bin\\Env.vbs -c %s %s %s","SYSTEM",lists[index].env_base,"")
    print(cmds)
    os.execute(cmds)

    
end


function resetEnv( f )
    -- body
	initpath="%SystemRoot%\\system32;%SystemRoot%;%SystemRoot%\\System32\\Wbem;%SYSTEMROOT%\\System32\\WindowsPowerShell\\v1.0;C:\\Program Files\\Microsoft SQL Server\\90\\Tools\\binn;C:\\Program Files (x86)\\GNU\\GnuPG\pub";
	cmds = string.format("@set %s=%s\n","PATH",initpath)
	f:write(cmds)
	cmds = string.format("@set %s=\n","LIBRARY_PATH")
	f:write(cmds)
	cmds = string.format("@set %s=\n","C_INCLUDE_PATH")
	f:write(cmds)
	cmds = string.format("@set %s=\n","CPLUS_INCLUDE_PATH")
	f:write(cmds)
end

----------------------------------------------------------------------------------------------
--Main Routine 
--
----------------------------------------------------------------------------------------------




--global variable
local path_list=""   --
local ret = -1
local env_mode=0  -- 0 tmp env  1 perment env
local config_file="config.lua"
local con
local top_dir
local init_path


print("load config file ....")
dofile(config_file)
 
if(develop_list == nil ) then
    print( string.format("Couldn't load '%s' files!",config_file) )
    os.exit(-1)
end   

f=io.open("tmp.bat","w+")
--Get current directory
con     =  io.popen("cd")
top_dir =  con:read("*line")

init_path = os.getenv("PATH")

if env_mode == 0 then
    os.execute("color 0F") 
else
    os.execute("color 0A") 
end
f:seek("set",0)




while true do
    -- os.execute("cls")
    Main_menu(develop_list)
    main_choice = get_choice(develop_list,#develop_list +5)

    if main_choice == 0 then
        break
    elseif  main_choice == 1  then
        if env_mode == 0 then
            path_list=""
        end
    elseif  main_choice == 2  then
        print("setup temp path env")
        env_mode = 0   ---temp mode
		f:seek("set",0)
        os.execute("color 0F") 
    elseif  main_choice == 3  then 
        print("setup  permanent env")
        env_mode = 1   --perment mode
		f:seek("set",0)
        os.execute("color 0A")  
		-- resetEnv(f)
 
    elseif  main_choice == 4  then
        -- 安装所有
		resetEnv(f)
        for i,v in ipairs(develop_list) do
            env_install(f,env_mode,"SYSTEM",top_dir,develop_list,i)
        end
    elseif main_choice == 5  then  
        -- 卸载所有
        for i,v in ipairs(develop_list) do
            env_uninstall(f,env_mode,"SYSTEM",top_dir,develop_list,i)
        end
    else
        -- 单独安装/或者卸载
        print(string.format("Please choose install/uninstall %s",develop_list[main_choice-5].name) )
        Sub_menu(develop_list)
        sub_choice = get_choice(develop_list,3)
        if sub_choice == 0 then
            break;
        elseif sub_choice ==1 then
            print("-------------------------------------------------------------------")
        elseif sub_choice ==2 then
            --install
            env_install(f,env_mode,"SYSTEM",top_dir,develop_list,main_choice-5)
        else
            --uninstall 
            env_uninstall(f,env_mode,"SYSTEM",top_dir,develop_list,main_choice-5)
        end        
    end
end


-- 有网友说如果是Win7以下系统，通过wmic设置后，是直接自动生效的，对于已加载的cmd或explorer当然是无法做到的。 
-- win7以上系统wmic设置后，仍然无法立即生效，这里查阅相关资料和其他网友的研究，可以通过setx进行设置

-- setx Path /K "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\Path\" /M
-- 如果环境变量不能立即生效，去环境变量设置界面打开一个下就生效了
if env_mode ~= 0 then  --永久设置环境变量
	-- cmds = string.format("wmic ENVIRONMENT where \"name='PATH' and username='<system>'\" set VariableValue=\"%s\"\n","\%PATH\%" )
	-- f:write(cmds)
	-- cmds = string.format("call bin\\InvalidateEnv\n")
	f:write(cmds)
else
    --f:write("@set init_work_root=%BASE_HOME%\r\n")
    --cmds = string.format("@set PATH=%s\\bin;%s\\bin\\gow;%%%s%%\n",top_dir,top_dir,"PATH")
    --f:write(cmds)
end


f:write("set\r\n")
f:close()

